package com.huanxing.cloud.security.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.huanxing.cloud.common.core.constant.SecurityConstants;
import com.huanxing.cloud.common.core.entity.Result;
import com.huanxing.cloud.security.entity.HuanxingUser;
import com.huanxing.cloud.security.service.HuanxingUserDetailsService;
import com.huanxing.cloud.upms.common.entity.SysUser;
import com.huanxing.cloud.upms.common.feign.FeignSysUserService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
 * 实现类
 *
 * @author lijx
 * @date 2022/6/10
 */
@Service
@AllArgsConstructor
public class HuanxingUserDetailsServiceImpl implements HuanxingUserDetailsService {
  private final FeignSysUserService feignSysUserService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    Result<SysUser> sysUserR =
        feignSysUserService.getUserInfo(username, SecurityConstants.SOURCE_IN);
    if (!sysUserR.isOk()) {
      throw new RuntimeException(sysUserR.getMsg());
    }
    return getUserDetails(sysUserR);
  }

  private UserDetails getUserDetails(Result<SysUser> result) {
    if (result == null || result.getData() == null) {
      throw new UsernameNotFoundException("用户不存在");
    }
    SysUser user = result.getData();
    Set<String> dbAuthsSet = new HashSet<>();
    if (ArrayUtil.isNotEmpty(user.getRoles())) {
      // 获取角色
      Arrays.stream(user.getRoles())
          .forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
      // 获取资源
      dbAuthsSet.addAll(Arrays.asList(user.getPermissions()));
    }
    Collection<? extends GrantedAuthority> authorities =
        AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
    return new HuanxingUser(
        user.getId(),
        null,
        "",
        null,
        user.getUsername(),
        user.getPassword(),
        true,
        true,
        true,
        true,
        authorities);
  }
}
